package org.jetlinks.pro.utils;

import org.hswebframework.ezorm.core.param.QueryParam;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.Optional;

/**
 * 滚动游标分页工具
 *
 * @author zhouhao
 * @since 1.10
 */
public class ScrollPagingUtils {

    public static final String SCROLL_ID_KEY = "scrollId";

    /**
     * 设置游标ID到查询条件
     *
     * @param param    查询条件
     * @param scrollId 游标ID
     * @param <T>      查询条件类型
     * @return 查询条件
     */
    public static <T extends QueryParam> T setScrollId(T param, String scrollId) {
        param.context(SCROLL_ID_KEY, scrollId);
        return param;
    }

    /**
     * 获取查询条件中的游标ID
     *
     * @param param 查询条件
     * @return 游标ID
     */
    public static Optional<String> getScrollId(QueryParam param) {
        return param
            .getContext(SCROLL_ID_KEY)
            .map(String::valueOf);
    }

    public static Optional<String> getScrollId(Map<String, Object> param) {
        if (CollectionUtils.isEmpty(param)) {
            return Optional.empty();
        }
        return Optional.ofNullable((String) param.get(SCROLL_ID_KEY));
    }
}
